package com.kuangchi.weixin.sginin.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @date HttpClient工具类
 */
public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get请求
     *
     * @return 请求结果
     */
    public static String doGet(String url) throws Exception {
        HttpClient client = new DefaultHttpClient();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        }
        return null;
    }

    public static byte[] doGetPicByte(String url) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        return EntityUtils.toByteArray(response.getEntity());
    }


    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url    请求地址
     * @param params 参数
     * @return 结果
     */
    public static String doPost(String url, Map params) throws Exception {
        BufferedReader in;
        // 定义HttpClient
        HttpClient client = new DefaultHttpClient();
        // 实例化HTTP方法
        HttpPost request = new HttpPost();
        request.setURI(new URI(url));
        // 设置参数
        List<NameValuePair> nvps = new ArrayList<>();
        for (Object o : params.keySet()) {
            String name = (String) o;
            String value = String.valueOf(params.get(name));
            nvps.add(new BasicNameValuePair(name, value));
        }
        request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            String nl = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line).append(nl);
            }
            in.close();
            return sb.toString();
        } else {
            System.out.println("状态码：" + code);
            return null;
        }
    }

    /**
     * post请求，参数为bean
     *
     * @param url   请求地址
     * @param param 参数
     * @return 结果
     * @throws Exception 异常
     */
    public static String doPostObject(String url, Object param) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建POST请求对象
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> list = new LinkedList<>();
        Map<String, String> map = new HashMap<>(16);
        Class<?> aClass = param.getClass();
        Arrays.asList(aClass.getDeclaredFields()).forEach(field -> {
            field.setAccessible(true);
            try {
                Object object = field.get(param);
                if (null != object) {
                    map.put(field.getName(), object instanceof String ? (String) object : JSONObject.toJSONString(object));
                }
            } catch (Exception e) {
                logger.error("调用第三方接口时，对象转换发生异常");
            }
        });
        map.forEach((key, value) -> list.add(new BasicNameValuePair(key, value))
        );

       // ttpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
        // 传输的类型
        httpPost.addHeader("Content-Type", "application/json");
        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 获得响应的实体对象
        HttpEntity entity = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        String result = EntityUtils.toString(entity, "UTF-8");
        response.close();
        httpClient.close();
        return result;
    }

    /**
     * post请求，参数包含文件,Object只支持List和String
     *
     * @param url     地址
     * @param files   文件
     * @param params  其他入参
     * @param fileKey 文件名
     * @return 结果
     * @throws Exception 异常
     */
    public static String doPostWithFile(String url, @NotNull List<InputStream> inputStreams, @NotNull Map<String, Object> params, String fileKey) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建POST请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置传输参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 文件流上传
        inputStreams.forEach(stream -> {
            //	文件传输http请求头(multipart/form-data)
            try {
                builder.addBinaryBody(fileKey, stream, ContentType.DEFAULT_BINARY,
                        "shangtang");
            } catch (Exception e) {
                logger.info("商汤图片同步时，图片转换失败");
            }
        });
        //	字节传输http请求头(application/json)
        ContentType contentType = ContentType.create("application/json", Charset.forName("UTF-8"));
        params.keySet().forEach(key ->
                {
                    Object value = params.get(key);
                    if (value instanceof String) {
                        builder.addTextBody(key, (String) value, contentType);
                    }
                    if (value instanceof List) {
                        for (int i = 0; i < ((List) value).size(); i++) {
                            builder.addTextBody(key, String.valueOf(((List) value).get(i)), contentType);
                        }
                    }
                }
        );
        httpPost.setEntity(builder.build());
        HttpResponse response = client.execute(httpPost);
        // 获得响应的实体对象
        HttpEntity entity = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        return EntityUtils.toString(entity, "UTF-8");
    }
    
    public static String doPostWithStringEntity(String url, String params) throws Exception {

        BufferedReader in;
        // 定义HttpClient
        HttpClient client = HttpClientBuilder.create().build();
        // 实例化HTTP方法
        HttpPost request = new HttpPost();
        request.setURI(new URI(url));
        request.setEntity(new StringEntity(params, "UTF-8"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();
        // 请求成功
        if (code == 200) {
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder("");
            String line = "";
            String nl = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line).append(nl);
            }
            in.close();
            return sb.toString();
        } else {
            return null;
        }
    }
    
    public static String httpPostWithJson(String url, String json) throws IOException {
        String result = "";
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            BasicResponseHandler handler = new BasicResponseHandler();
            //解决中文乱码问题
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            result = httpClient.execute(httpPost, handler);
            return result;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}